﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace VoteList.VotesRank
{
    public class Rank
    {
        /*private string mAccountName;
        private int mVotesNumber;*/

        public int Order
        {
            get;
            set;
        }

        public string AccountName
        {
            get;
            set;
        }

        public string VotesNumber
        {
            get;
            set;
        }
    }

    public partial class VotesRankUserControl : UserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
                this.GridView1.DataSource = GetRankInfo();
                this.GridView1.DataBind();
            }
        }

        void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex<4)
            {
                e.Row.Cells[0].ForeColor = System.Drawing.Color.Red;
            }
        }

        private List<Rank> GetRankInfo()
        {
            Dictionary<string, int> rankTable = new Dictionary<string, int>();
            Dictionary<string, string> lastVotedTimeTable = new Dictionary<string, string>();

            SPList list = SPContext.Current.Site.RootWeb.Lists[Define.DATALISTNAME];

            foreach (SPListItem item in list.Items)
            {
                try
                {
                    string voteStr = item[Define.COLUMN_VOTE] != null ? item[Define.COLUMN_VOTE].ToString() : string.Empty;

                    string[] voteInfos = voteStr.Trim().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                    DateTime dateTimeA = DateTime.MinValue;
                    DateTime dateTimeB = DateTime.MinValue;

                    foreach (string userRow in voteInfos)
                    {
                        try
                        {
                            string[] userInfos = userRow.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            string userName = userInfos[0];
                            string dateTime = userInfos[1];
                            if (rankTable.ContainsKey(userName))
                            {
                                ++rankTable[userName];
                            }
                            else
                            {
                                rankTable.Add(userName, 1);
                            }

                            if (lastVotedTimeTable.ContainsKey(userName))
                            {
                                dateTimeA = Convert.ToDateTime(lastVotedTimeTable[userName]);
                                dateTimeB = Convert.ToDateTime(dateTime);

                                if (DateTime.Compare(dateTimeA, dateTimeB) < 0)
                                {
                                    lastVotedTimeTable[userName] = dateTime;
                                }
                            }
                            else
                            {
                                lastVotedTimeTable.Add(userName, dateTime);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                catch
                { }
            }           

            return SortResult(rankTable, lastVotedTimeTable);
        }

        public string GetUserAccount(string loginName)
        {
            string accountName = loginName;
            string userName = string.Empty;

            int index = accountName.IndexOf("\\");

            if (index > -1)
            {
                accountName = accountName.Substring(index + 1);
            }

            SPWeb web = SPContext.Current.Web;

            SPUser user = web.EnsureUser(loginName);

            userName = user.Name;

            int index1 = userName.IndexOf("(");
            if (index1 > -1)
            {
                userName = userName.Substring(0, index1);
            }
            accountName = string.Format("{0}({1})", userName, accountName);

            return accountName;
        }

        private List<Rank> SortResult(Dictionary<string, int> voteResult, Dictionary<string, string> voteTime)
        {
            List<Rank> rankInfos = new List<Rank>();            

            while (rankInfos.Count < 5 && voteResult.Count > 0)
            {
                int maxNum = 0;
                DateTime time = DateTime.MaxValue;
                string curUser = null;

                foreach (string user in voteResult.Keys)
                {
                    int count = voteResult[user];
                    if (count > maxNum || (count == maxNum && DateTime.Compare(Convert.ToDateTime(voteTime[user]), time) < 0))
                    {
                        time = Convert.ToDateTime(voteTime[user]);
                        maxNum = count;
                        curUser = user;
                    }
                }

                Rank rank = new Rank();
                rank.AccountName = GetUserAccount(curUser);
                rank.VotesNumber = string.Format("{0}票", maxNum);
                rank.Order = rankInfos.Count + 1;
                rankInfos.Add(rank);
                voteResult.Remove(curUser);
                voteTime.Remove(curUser);
            }

            for (int index = rankInfos.Count + 1; index <= 5; index++)
            {
                Rank rank = new Rank();
                rank.AccountName = "暂无候选人";
                rank.VotesNumber = "0票";
                rank.Order = index;
                rankInfos.Add(rank);
            }

            return rankInfos;
        }
    }
}
